package com.kangye.exam.controller;

import com.kangye.exam.bean.Paper;
import com.kangye.exam.bean.Student;
import com.kangye.exam.bean.StudentPaper;
import com.kangye.exam.service.StudentTestService;
import com.kangye.exam.utils.JsonUtil;
import com.kangye.exam.utils.RedisTool;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/exam")
public class StudentExamController {
    @Resource
    private RedisTool redisTool;
    @Resource
    private StudentTestService sts;


    //试卷中心加载
    @RequestMapping("/center_loading")
    public Object test_center_lording(HttpServletRequest req,HttpServletResponse resp,Integer stuId) {
        String session_id = req.getSession().getId();
        Map<String,Object> map = new HashMap<>();
        Student student = new Student();
        if (stuId==null){
            map.put("code",-1);//传参不合法
            return map;
        }
        if ( redisTool.hget("stu",session_id)!=null){
            String stu = redisTool.hget("stu",session_id).toString();//获取redis中学生对象
            student = JsonUtil.json2Bean(stu,Student.class);
        }else{
            student.setStudentId(stuId);
        }
        List<Paper> papers = sts.testLoading(student);     //获取试卷
        if (papers.size()==0){
            map.put("code",-1);//没有需要做的试卷
            return map;
        }
        redisTool.hset("stu_paper_list",session_id,JsonUtil.list2Json(papers),3600);//把获取的试卷列表存入redis中
        map.put("papers",papers);
        map.put("code",0);
        return map;
    }

    //加载试卷
    @RequestMapping("/paper_loading")
    public Object paper_lording(HttpSession session,Integer paperId){
        Map<String,Object> map = new HashMap<>();
        String session_id = session.getId();
        if (paperId==null){
            map.put("code",-1);//传参不合法
            return map;
        }
        Paper paper = new Paper();
        if (redisTool.hget("stu_paper_list",session_id)!=null){
            String paperlist = redisTool.hget("stu_paper_list",session_id).toString();//根据session的id取出试卷表
            List<Paper> papers = JsonUtil.json2List(paperlist,Paper.class);
            for (Paper p: papers) {
                if (p.getPaperId()==paperId){
                    paper = p;
                }
            }
        }else{
            paper = sts.getPaper(paperId);
        }
        String paperUrl = paper.getPaperPath();//获取到试卷路径
        //根据路径获取到文件
        //下列整合时需改
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+ "paper/"+paperUrl+".json";
        File file = new File(path);
        if (!file.exists()){
            map.put("code",2);    //如果文件不存在则
            return map;
        }
        String str = this.jsonRead(file);//解析json文件为String格式
        map.put("paper_id",paper.getPaperId());
        map.put("code",0);
        map.put("paper",str);
        return map;
    }

    //获取答案
    @RequestMapping("/getAnswer")
    public Object getanswer(String data, Model model, HttpSession session, Integer paperId,Integer stuId){
        Map<String,Object> map = new HashMap<>();
        Map<String,String> map1 = new HashMap<>();
        map1 = JsonUtil.json2Map(data);
        String session_id = session.getId();
        Student student = new Student();
        if ( redisTool.hget("stu",session_id)!=null){
            String stu = redisTool.hget("stu",session_id).toString();//获取redis中学生对象
            student = JsonUtil.json2Bean(stu,Student.class);//转换为student对象格式
        }else{
            Student student1 = sts.getStudent(stuId);
            if (student1==null){
                map.put("code",-1);
                return map;
            }
            student.setStudentName(student1.getStudentName());
        }
        Paper paper = new Paper();
        if (redisTool.hget("stu_paper_list",session_id)!=null){
            String paperlist = redisTool.hget("stu_paper_list",session_id).toString();//根据session的id取出试卷表
            List<Paper> papers = JsonUtil.json2List(paperlist,Paper.class);
            for (Paper p: papers) {
                if (p.getPaperId()==paperId){
                    paper = p;
                }
            }
        }else{
            paper = sts.getPaper(paperId);
        }
        if (paper==null){
            map.put("code",-1);
            return map;
        }
        //json文件名格式：学生姓名+试卷名.json
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+ "paper/" +
                student.getStudentName()+paper.getPaperName()+
                ".json";
        File file = new File(path);
        try {
            if (!file.getParentFile().exists()) {
                // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(String.valueOf(data));
            write.flush();
            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Date date = new Date();
        java.sql.Timestamp sqldate=new java.sql.Timestamp(date.getTime());//获取数据库格式的时间类型
        StudentPaper studentpaper = new StudentPaper();
        studentpaper.setPaperId(paperId);
        studentpaper.setStudentPath(student.getStudentName()+paper.getPaperName());
        studentpaper.setStudentTime(sqldate);
        studentpaper.setStudentId(1);//因为sessionId不稳定所以先直接传值测试
        if (sts.addAnswer(studentpaper)){
            map.put("code",-1);
        }
        map.put("code",0);
        return map;
    }
    //文件的读取
    private String jsonRead(File file){
        String jsonStr;
        try {
            FileReader fileReader = new FileReader(file);//
            Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8");
            int ch=0;
            StringBuffer sb = new StringBuffer();
            while ((ch=reader.read())!=-1){
                sb.append((char)ch);
            }
            fileReader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (Exception e) {
            return null;
        }
    }
}
